package com.example.goodpet;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.example.goodpet.R;
import com.example.goodpet.activity.MainActivity;
import com.example.goodpet.bean.UpdateInfo;
import com.example.goodpet.bean.User;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.AppNetConfig;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.SecurityUtils;
import com.example.goodpet.utils.UIUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.interfaces.EaseMessageCallback;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Welcome extends FragmentActivity {


    private static final int MESSAGE_MAIN = 1;
    private static final int WHAT_DOWNLOAD_VERSION_SUCCESS = 2;
    private static final int WHAT_DOWNLOAD_FAIL = 3;
    private static final int WHAT_DOWNLOAD_APK_SUCCESS = 4;

    private long startTime;

    private Handler handler = new Handler(Looper.myLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_MAIN:
                    startActivity(new Intent(Welcome.this, MainActivity.class));
                    ActivityManager.getInstance().removeCurrent();
                    break;

                case WHAT_DOWNLOAD_VERSION_SUCCESS://获取了服务器端返回的版本信息
                    String version = getVersion();
                    if (version.equals(updateInfo.version)) {//版本相同
                        Toast.makeText(Welcome.this, "已经是最新版应用", Toast.LENGTH_SHORT).show();
                        toMain();
                    } else {
                        showDownloadDialog();
                    }
                    break;
                case WHAT_DOWNLOAD_FAIL:
                    Toast.makeText(Welcome.this, "下载应用文件失败", Toast.LENGTH_SHORT).show();
                    toMain();
                    break;
                case WHAT_DOWNLOAD_APK_SUCCESS:
                    installApk();
                    break;
            }
        }
    };
    private UpdateInfo updateInfo;
    private LinearLayout lyWelcome;
    private HomeService homeService;
    private TextView appName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 去掉窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏顶部的状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_welcome);

        //将当前的activity添加到ActivityManager中
        ActivityManager.getInstance().addActivity(this);
        //lyWelcome=findViewById(R.id.lyWelcome);
        appName=findViewById(R.id.app_name);
        //启动动画
        //startAnimation();

        homeService= RetrofitSingleton.getRetrofitNetConfig().create(HomeService.class);
        appName.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/jf-openhuninn-1.0.ttf"));
        //联网更新应用的操作
        updateApp();
    }

    /**
     * 安装apk
     */
    private void installApk() {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri apkUri = FileProvider.getUriForFile(this, "com.example.goodpet.fileProvider", apkFile);
        //Uri apkUri = Uri.parse("content:" + apkFile.getAbsolutePath());
        //intent.setData(apkUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(intent);

        //startActivity(intent);
    }

    private ProgressDialog dialog;
    private File apkFile;

    /**
     * 显示是否需要联网下载最新版本apk的Dialog
     */
    private void showDownloadDialog() {
        new AlertDialog.Builder(this)
                .setTitle("下载最新版本")
                .setMessage(updateInfo.desc)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showDownLoad();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMain();
                    }
                })
                .show();
    }

    /**
     * 联网下载指定url地址对应的apk文件
     * 1.提供ProgressDialog
     * 2.提供本地的存储文件
     * 3.联网下载数据
     * 4.安装
     */
    private void showDownLoad() {
        //1.提供ProgressDialog
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//水平显示
        dialog.setCancelable(false);
        dialog.show();
        //2.提供本地的存储文件:sd卡路径1
        String filePath = this.getExternalFilesDir(null) + "/update_app.apk";
        apkFile = new File(filePath);
        //3.联网下载数据
        new Thread() {
            public void run() {
                try {
                    downloadAPk();
                    handler.sendEmptyMessage(WHAT_DOWNLOAD_APK_SUCCESS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private void downloadAPk() throws Exception {
        FileOutputStream fos = new FileOutputStream(apkFile);
        String path = updateInfo.apkUrl;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestMethod("GET");

        conn.connect();
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            dialog.setMax(conn.getContentLength());
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);

                dialog.incrementProgressBy(len);
                //Thread.sleep(2);
            }
            dialog.dismiss();
            //暂且使用throws的方式处理异常了
            is.close();
            fos.close();
        } else {
            handler.sendEmptyMessage(WHAT_DOWNLOAD_FAIL);
        }

        //关闭连接
        conn.disconnect();
    }


    private void updateApp() {
        //获取系统当前的时间
        startTime = System.currentTimeMillis();

        boolean isConnected = isConnected();
        if (!isConnected) {
            Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
            toMain();
        } else {
            homeService.getUpdateInfo().enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    ResponseBody body = response.body();
                    if (body!=null){
                        try {
                            String json = body.string();
                            updateInfo=new Gson().fromJson(json,UpdateInfo.class);
                            handler.sendEmptyMessage(WHAT_DOWNLOAD_VERSION_SUCCESS);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    UIUtils.toast("连接服务器失败，无法获取更新",false);
                    toMain();
                }
            });
        }


    }

    /**
     * 通过发送延迟消息，进入主界面
     */
    private void toMain() {
        long currentTimeMillis = System.currentTimeMillis();
        long delayTime = 2000 - (currentTimeMillis - startTime);
        if (delayTime < 0) {
            delayTime = 0;
        }

        //发送延迟消息
        handler.sendEmptyMessageDelayed(MESSAGE_MAIN, delayTime);
    }

    /**
     * 判断是否可以联网
     *
     * @return
     */
    private boolean isConnected() {
        boolean connected = false;

        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            connected = networkInfo.isConnected();
        }
        return connected;

    }

    /**
     * 当前版本号
     *
     * @return
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //e.printStackTrace(); //如果找不到对应的应用包信息, 就返回"未知版本"
        }
        return version;
    }


    private void startAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);//0:完全透明 1：完全不透明
        alphaAnimation.setDuration(3000);
        alphaAnimation.setInterpolator(new AccelerateInterpolator());//设置动画的变化率
        //启动动画
        //lyWelcome.startAnimation(alphaAnimation);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.getHandler().removeCallbacksAndMessages(null);
    }
}